package tokenmem

import (
	"errors"
	"sync"
	"gitee.com/zxs-micro/zxs-micro-auth/grpc/authserver/model"
)

type LocalMem struct {
	l sync.Mutex
	//token对应用户结构体
	mems map[string]*model.TokenModel
}

var locals *LocalMem

func NewLocalMem() {
	if locals == nil {
		locals = new(LocalMem)
		locals.mems = make(map[string]*model.TokenModel)
	}
}

func (l *LocalMem) MemType() string {
	return "local"
}
func (l *LocalMem) GetToken(t string) (*model.TokenModel, error) {
	l.l.Lock()
	defer l.l.Unlock()
	m, ok := l.mems[t]
	if ok {
		return m, nil
	}
	return nil, errors.New("token无效！")
}
func (l *LocalMem) AddToken(t string, u *model.TokenModel) error {
	l.l.Lock()
	defer l.l.Unlock()
	if _, ok := l.mems[t]; ok {
		return errors.New("用户已登录")
	}
	l.mems[t] = u
	return nil
}
func (l *LocalMem) DeleteToken(t string) error {
	l.l.Lock()
	delete(l.mems, t)
	l.l.Unlock()
	return nil
}
